package com.kangyi.admin.service.Impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.admin.mapper.*;
import com.kangyi.admin.service.UserService;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.dto.BulkOperationDTO;
import com.kangyi.dto.UserPageQueryDTO;
import com.kangyi.entity.*;
import com.kangyi.exception.PermissionsException;
import com.kangyi.result.UserPageResult;
import com.kangyi.vo.AdminUserVO;
import com.kangyi.vo.UserPageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Blank
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private UserComplaintMapper userComplaintMapper;

    @Autowired
    private UserComplaintImgMapper userComplaintImgMapper;

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private ReviewImageMapper reviewImageMapper;

    @Autowired
    private ReviewReplyMapper reviewReplyMapper;

    @Autowired
    private ActivitiesSignupMapper activitiesSignupMapper;

    @Autowired
    private NursingHomeBookingMapper nursingHomeBookingMapper;

    @Autowired
    private NursingHomeFavoriteMapper nursingHomeFavoriteMapper;

    @Autowired
    private GuestsStayingMapper guestsStayingMapper;

    @Autowired
    private HealthInfoMapper healthInfoMapper;

    @Autowired
    private FourHighMapper fourHighMapper;

    @Autowired
    private NursingHomeApplicationMapper nursingHomeApplicationMapper;

    //调用后检查当前线程id是否有足够的权限进行后续操作
    public void validateUserPermissions() {
        Integer currentId = BaseContext.getCurrentId();
        AdminUserVO adminUserVO = adminUserMapper.selectById(currentId);
        if (!adminUserVO.getPermissions().equals(1)) {
            throw new PermissionsException(MessageConstant.INSUFFICIENT_PRIVILEGE);
        }
    }

    @Override
    public UserPageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        validateUserPermissions();
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        Page<UserPageQueryVO> page = userMapper.pageQuery(userPageQueryDTO);
        long total = page.getTotal();
        List<UserPageQueryVO> result = page.getResult();

        int enable = 0;
        int disable = 0;

        for (UserPageQueryVO vo : result) {
            if (vo.getStatus() == 1) {
                enable++;
            } else if (vo.getStatus() == 2) {
                disable++;
            }
        }

        return new UserPageResult(total,result,total,enable,disable);
    }

    @Override
    public void bulkOperation(BulkOperationDTO bulkOperationDTO) {
        validateUserPermissions();
        for (Integer id : bulkOperationDTO.getIds()) {
            User build = User.builder()
                    .id(id)
                    .status(bulkOperationDTO.getType())
                    .build();
            userMapper.bulkOperation(build);
        }
    }

    @Override
    @Transactional
    public void deleteUserAccount(List<Integer> ids) {
        validateUserPermissions(); // 将权限验证移到循环外部

        for (Integer id : ids) {
            try {
                // 清理反馈意见及相关图片
                clearUserComplaints(id);
                // 清理评论及相关图片和回复
                clearUserReviews(id);
                // 清理活动报名记录
                activitiesSignupMapper.deleteByUserId(id);
                // 清理养老院预约记录
                nursingHomeBookingMapper.deleteByUserId(id);
                // 清理收藏记录
                nursingHomeFavoriteMapper.deleteByUserId(id);
                // 清理入住人信息及健康信息
                clearUserGuests(id);
                // 清理入驻养老院记录
                nursingHomeApplicationMapper.deleteByUserId(id);
                // 删除用户账号
                userMapper.deleteById(id);
            } catch (Exception e) {
                // 处理异常，例如记录日志或抛出业务异常
                throw new RuntimeException("删除用户账号时出现异常：" + e.getMessage(), e);
            }
        }
    }

    private void clearUserComplaints(Integer userId) {
        List<UserComplaint> userComplaintList = userComplaintMapper.getByUserId(userId);
        if (!CollUtil.isEmpty(userComplaintList)) {
            for (UserComplaint userComplaint : userComplaintList) {
                Integer userComplaintId = userComplaint.getId();
                userComplaintImgMapper.deleteByUserId(userComplaintId);
            }
            userComplaintMapper.deleteByUserId(userId);
        }
    }

    private void clearUserReviews(Integer userId) {
        List<NursingHomeReview> nursingHomeReviewList = reviewMapper.getByUserId(userId);
        if (!CollUtil.isEmpty(nursingHomeReviewList)) {
            for (NursingHomeReview nursingHomeReview : nursingHomeReviewList) {
                Integer reviewId = nursingHomeReview.getId();
                reviewImageMapper.deleteById(reviewId);
                reviewReplyMapper.deleteById(reviewId);
            }
            reviewMapper.deleteByUserId(userId);
        }
    }

    private void clearUserGuests(Integer userId) {
        List<GuestsStaying> guestsStayingList = guestsStayingMapper.getByUserId(userId);
        if (!CollUtil.isEmpty(guestsStayingList)) {
            for (GuestsStaying guestsStaying : guestsStayingList) {
                Integer guestId = guestsStaying.getId();
                healthInfoMapper.deleteByGuestId(guestId);
                fourHighMapper.deleteByGuestId(guestId);
            }
            guestsStayingMapper.deleteByUserId(userId);
        }
    }
}
